package com.guotong.permission;

import com.guotong.common.exception.GlobalException;
import com.guotong.sysUser.SysUser;
import com.guotong.sysUser.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    SysUserService sysUserService;

    /**
     * 授权方法
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String username = (String) principalCollection.getPrimaryPrincipal();
        System.out.println(username + "====================");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        simpleAuthorizationInfo.setRoles();
        return simpleAuthorizationInfo;
    }

    /**
     * 认证方法
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /**
         *  获取用户名
         */
       UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String username = token.getUsername();
       if(username == null ) {
           return null;
       }
        SysUser sysUser = sysUserService.findByUsername(username);

        if (sysUser == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getPassword(), token.getUsername());
    }
}
